<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单管理 - 仓库管理系统</title>
    <link rel="stylesheet" href="https://unpkg.com/layui@2.8.18/dist/css/layui.css">
    <style>
        body {
            background-color: #f2f2f2;
            margin: 0;
            padding: 0;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            margin: 0;
            font-size: 24px;
            font-weight: 300;
        }
        
        .main-container {
            display: flex;
            height: calc(100vh - 70px);
        }
        
        .sidebar {
            width: 250px;
            background-color: #fff;
            box-shadow: 2px 0 4px rgba(0,0,0,0.1);
            overflow-y: auto;
        }
        
        .content {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
        }
        
        .nav-item {
            padding: 15px 20px;
            border-bottom: 1px solid #f0f0f0;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
        }
        
        .nav-item:hover {
            background-color: #f8f9fa;
            color: #667eea;
        }
        
        .nav-item.active {
            background-color: #667eea;
            color: white;
        }
        
        .nav-item i {
            margin-right: 10px;
            font-size: 16px;
        }
        
        .nav-item span {
            font-size: 14px;
        }
        
        .dashboard {
            background: white;
            border-radius: 8px;
            padding: 30px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .dashboard h2 {
            color: #333;
            margin-bottom: 30px;
            font-weight: 300;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }
        
        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 10px;
        }
        
        .search-box {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .search-input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
        }
        
        .btn-primary {
            background-color: #667eea;
            color: white;
        }
        
        .btn-primary:hover {
            background-color: #5a6fd8;
        }
        
        .btn-success {
            background-color: #52c41a;
            color: white;
        }
        
        .btn-success:hover {
            background-color: #49aa15;
        }
        
        .btn-warning {
            background-color: #faad14;
            color: white;
        }
        
        .btn-warning:hover {
            background-color: #d48806;
        }
        
        .btn-danger {
            background-color: #ff4d4f;
            color: white;
        }
        
        .btn-danger:hover {
            background-color: #cf1322;
        }
        
        .btn-info {
            background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
            color: white;
            box-shadow: 0 2px 4px rgba(23, 162, 184, 0.3);
        }
        
        .btn-info:hover {
            background: linear-gradient(135deg, #138496 0%, #117a8b 100%);
            box-shadow: 0 4px 8px rgba(23, 162, 184, 0.4);
            transform: translateY(-1px);
        }
        
        .btn-info i {
            margin-right: 4px;
            font-size: 14px;
        }
        
        .order-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        
        .order-table th,
        .order-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .order-table th {
            background-color: #fafafa;
            font-weight: 500;
            color: #333;
        }
        
        .order-table tr:hover {
            background-color: #f8f9fa;
        }
        
        .status-pending {
            color: #faad14;
            font-weight: 500;
        }
        
        .status-processing {
            color: #1890ff;
            font-weight: 500;
        }
        
        .status-completed {
            color: #52c41a;
            font-weight: 500;
        }
        
        .status-cancelled {
            color: #ff4d4f;
            font-weight: 500;
        }
        
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        
        .btn-sm {
            padding: 4px 8px;
            font-size: 12px;
        }
        
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        
        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 30px;
            border-radius: 8px;
            width: 80%;
            max-width: 800px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
            max-height: 80vh;
            overflow-y: auto;
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .modal-title {
            font-size: 18px;
            font-weight: 500;
            color: #333;
        }
        
        .close {
            font-size: 24px;
            font-weight: bold;
            cursor: pointer;
            color: #999;
        }
        
        .close:hover {
            color: #333;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
        }
        
        .form-input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            box-sizing: border-box;
        }
        
        .form-input:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .form-textarea {
            resize: vertical;
            min-height: 80px;
        }
        
        .form-row {
            display: flex;
            gap: 15px;
        }
        
        .form-col {
            flex: 1;
        }
        
        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 30px;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
            gap: 8px;
            align-items: center;
        }
        
        .pagination button {
            padding: 8px 12px;
            border: 1px solid #ddd;
            background: white;
            cursor: pointer;
            border-radius: 4px;
            font-size: 14px;
            transition: all 0.3s ease;
            min-width: 40px;
        }
        
        .pagination button:hover {
            background-color: #f8f9fa;
            border-color: #667eea;
        }
        
        .pagination button.active {
            background-color: #667eea;
            color: white;
            border-color: #667eea;
        }
        
        .pagination button:disabled {
            background-color: #f5f5f5;
            color: #ccc;
            cursor: not-allowed;
            border-color: #ddd;
        }
        
        .loading {
            text-align: center;
            padding: 50px;
            color: #999;
        }
        
        .no-data {
            text-align: center;
            padding: 50px;
            color: #999;
        }
        
        .stats-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        .stat-card h3 {
            margin: 0 0 10px 0;
            font-size: 28px;
            font-weight: 300;
        }
        
        .stat-card p {
            margin: 0;
            font-size: 14px;
            opacity: 0.9;
        }
        
        .order-details-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        
        .order-details-table th,
        .order-details-table td {
            padding: 8px;
            text-align: left;
            border: 1px solid #ddd;
            font-size: 12px;
        }
        
        .order-details-table th {
            background-color: #f5f5f5;
            font-weight: 500;
        }
        
        .add-detail-btn {
            background-color: #52c41a;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            margin-top: 10px;
        }
        
        .remove-detail-btn {
            background-color: #ff4d4f;
            color: white;
            border: none;
            padding: 2px 6px;
            border-radius: 3px;
            cursor: pointer;
            font-size: 10px;
        }
        
        .customer-select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
                 .product-select {
             width: 100%;
             padding: 8px;
             border: 1px solid #ddd;
             border-radius: 4px;
             font-size: 12px;
         }
         
         /* 订单预览样式 */
         .preview-content {
             max-height: 60vh;
             overflow-y: auto;
         }
         
         .preview-section {
             margin-bottom: 25px;
         }
         
         .preview-section h4 {
             color: #333;
             margin-bottom: 15px;
             padding-bottom: 8px;
             border-bottom: 2px solid #667eea;
             font-weight: 500;
         }
         
         .preview-info {
             background-color: #f8f9fa;
             padding: 15px;
             border-radius: 6px;
             border-left: 4px solid #667eea;
         }
         
         .info-row {
             display: flex;
             margin-bottom: 10px;
             align-items: flex-start;
         }
         
         .info-row:last-child {
             margin-bottom: 0;
         }
         
         .info-label {
             font-weight: 500;
             color: #666;
             min-width: 100px;
             flex-shrink: 0;
         }
         
         .info-value {
             color: #333;
             flex: 1;
         }
         
         .preview-table-container {
             overflow-x: auto;
             border: 1px solid #ddd;
             border-radius: 6px;
         }
         
         .preview-table {
             width: 100%;
             border-collapse: collapse;
             font-size: 13px;
         }
         
         .preview-table th,
         .preview-table td {
             padding: 10px 8px;
             text-align: left;
             border-bottom: 1px solid #f0f0f0;
         }
         
         .preview-table th {
             background-color: #f5f5f5;
             font-weight: 500;
             color: #333;
             position: sticky;
             top: 0;
         }
         
         .preview-table tr:hover {
             background-color: #f8f9fa;
         }
         
         .preview-summary {
             background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
             color: white;
             padding: 20px;
             border-radius: 8px;
             box-shadow: 0 4px 8px rgba(0,0,0,0.1);
         }
         
         .summary-row {
             display: flex;
             justify-content: space-between;
             align-items: center;
             margin-bottom: 10px;
         }
         
         .summary-row:last-child {
             margin-bottom: 0;
         }
         
         .summary-label {
             font-weight: 500;
             opacity: 0.9;
         }
         
         .summary-value {
             font-weight: 600;
             font-size: 16px;
         }
         
         .quantity-display {
             display: flex;
             gap: 10px;
             align-items: center;
         }
         
         .quantity-item {
             background-color: rgba(255,255,255,0.2);
             padding: 4px 8px;
             border-radius: 4px;
             font-size: 12px;
         }
    </style>
</head>
<body>
    <!-- 头部 -->
    <div class="header">
        <h1><i class="layui-icon layui-icon-form"></i> 订单管理</h1>
    </div>
    
    <!-- 主容器 -->
    <div class="main-container">
        <!-- 左侧导航栏 -->
        <div class="sidebar">
            <div class="nav-item" onclick="goToHome()">
                <i class="layui-icon layui-icon-home"></i>
                <span>系统首页</span>
            </div>
            <div class="nav-item" onclick="goToCustomers()">
                <i class="layui-icon layui-icon-user"></i>
                <span>客户管理</span>
            </div>
            <div class="nav-item" onclick="goToProducts()">
                <i class="layui-icon layui-icon-cart"></i>
                <span>商品管理</span>
            </div>
            <div class="nav-item" onclick="goToCategories()">
                <i class="layui-icon layui-icon-tabs"></i>
                <span>分类管理</span>
            </div>
            <div class="nav-item active" onclick="showOrders()">
                <i class="layui-icon layui-icon-form"></i>
                <span>订单管理</span>
            </div>
            <div class="nav-item" onclick="goToStockIn()">
                <i class="layui-icon layui-icon-add-1"></i>
                <span>入库管理</span>
            </div>
            <div class="nav-item" onclick="goToStockOut()">
                <i class="layui-icon layui-icon-delete"></i>
                <span>出库管理</span>
            </div>
            <div class="nav-item" onclick="goToReports()">
                <i class="layui-icon layui-icon-chart"></i>
                <span>统计报表</span>
            </div>
            <div class="nav-item" onclick="goToSettings()">
                <i class="layui-icon layui-icon-set"></i>
                <span>系统设置</span>
            </div>
        </div>
        
        <!-- 主内容区域 -->
        <div class="content">
            <div class="dashboard">
                <h2><i class="layui-icon layui-icon-form"></i> 订单管理</h2>
                
                <!-- 统计卡片 -->
                <div class="stats-cards">
                    <div class="stat-card">
                        <h3 id="totalOrders">0</h3>
                        <p>订单总数</p>
                    </div>
                    <div class="stat-card">
                        <h3 id="pendingOrders">0</h3>
                        <p>待处理订单</p>
                    </div>
                    <div class="stat-card">
                        <h3 id="completedOrders">0</h3>
                        <p>已完成订单</p>
                    </div>
                    <div class="stat-card">
                        <h3 id="todayOrders">0</h3>
                        <p>今日订单</p>
                    </div>
                </div>
                
                <!-- 工具栏 -->
                <div class="toolbar">
                    <div class="search-box">
                        <input type="text" id="searchOrderNumber" class="search-input" placeholder="按订单号搜索">
                        <input type="text" id="searchCustomer" class="search-input" placeholder="按客户搜索">
                        <select id="statusFilter" class="search-input" style="width: auto;" onchange="filterByStatus()">
                            <option value="">全部状态</option>
                            <option value="PENDING">待处理</option>
                            <option value="PROCESSING">处理中</option>
                            <option value="COMPLETED">已完成</option>
                            <option value="CANCELLED">已取消</option>
                        </select>
                        <button class="btn btn-primary" onclick="searchOrders()">
                            <i class="layui-icon layui-icon-search"></i> 搜索
                        </button>
                        <button class="btn btn-success" onclick="resetSearch()">
                            <i class="layui-icon layui-icon-refresh"></i> 重置
                        </button>
                        <select id="pageSizeSelect" class="search-input" style="width: auto;" onchange="changePageSize()">
                            <option value="10">每页10条</option>
                            <option value="20">每页20条</option>
                            <option value="50">每页50条</option>
                            <option value="100">每页100条</option>
                        </select>
                    </div>
                    <button class="btn btn-primary" onclick="showAddOrderModal()">
                        <i class="layui-icon layui-icon-add-1"></i> 新建订单
                    </button>
                </div>
                

                
                <!-- 订单列表 -->
                <div id="orderList">
                    <div class="loading">
                        <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>
                        <p>加载中...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 新建/编辑订单模态框 -->
    <div id="orderModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title" id="orderModalTitle">新建订单</h3>
                <span class="close" onclick="closeOrderModal()">&times;</span>
            </div>
            <form id="orderForm">
                <input type="hidden" id="orderId">
                <input type="hidden" id="orderNumber">
                <div class="form-row">
                    <div class="form-col">
                        <div class="form-group">
                            <label class="form-label">客户 *</label>
                            <select id="orderCustomer" class="customer-select" required>
                                <option value="">请选择客户</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-col">
                        <div class="form-group">
                            <label class="form-label">客户电话</label>
                            <input type="text" id="customerPhone" class="form-input">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">客户地址</label>
                    <input type="text" id="customerAddress" class="form-input">
                </div>
                <div class="form-group">
                    <label class="form-label">订单明细 *</label>
                    <div id="orderDetailsContainer">
                                                 <table class="order-details-table">
                             <thead>
                                 <tr>
                                     <th>商品</th>
                                     <th>数量</th>
                                     <th>单位</th>
                                     <th>单价</th>
                                     <th>小计</th>
                                     <th>操作</th>
                                 </tr>
                             </thead>
                             <tbody id="orderDetailsBody">
                             </tbody>
                         </table>
                        <button type="button" class="add-detail-btn" onclick="addOrderDetail()">
                            <i class="layui-icon layui-icon-add-1"></i> 添加商品
                        </button>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-col">
                        <div class="form-group">
                            <label class="form-label">总金额</label>
                            <input type="text" id="totalAmount" class="form-input" readonly>
                        </div>
                    </div>
                    <div class="form-col">
                        <div class="form-group">
                            <label class="form-label">操作人</label>
                            <input type="text" id="operator" class="form-input">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">备注</label>
                    <textarea id="remark" class="form-input form-textarea"></textarea>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn" onclick="closeOrderModal()">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>
    
         <!-- 出库操作模态框 -->
     <div id="stockOutModal" class="modal">
         <div class="modal-content">
             <div class="modal-header">
                 <h3 class="modal-title">出库操作</h3>
                 <span class="close" onclick="closeStockOutModal()">&times;</span>
             </div>
             <div class="form-group">
                 <label class="form-label">操作人 *</label>
                 <input type="text" id="stockOutOperator" class="form-input" placeholder="请输入操作人姓名">
             </div>
             <div class="form-group">
                 <label class="form-label">订单信息</label>
                 <div id="stockOutOrderInfo" style="background-color: #f8f9fa; padding: 15px; border-radius: 4px;">
                     <!-- 订单信息将在这里显示 -->
                 </div>
             </div>
             <div class="form-actions">
                 <button type="button" class="btn" onclick="closeStockOutModal()">取消</button>
                 <button type="button" class="btn btn-success" onclick="confirmStockOut()">确认出库</button>
             </div>
         </div>
     </div>
     
     <!-- 订单预览模态框 -->
     <div id="orderPreviewModal" class="modal">
         <div class="modal-content">
             <div class="modal-header">
                 <h3 class="modal-title">订单预览</h3>
                 <span class="close" onclick="closeOrderPreviewModal()">&times;</span>
             </div>
             <div class="preview-content">
                 <div class="preview-section">
                     <h4>基本信息</h4>
                     <div class="preview-info">
                         <div class="info-row">
                             <span class="info-label">订单号：</span>
                             <span class="info-value" id="previewOrderNumber">-</span>
                         </div>
                         <div class="info-row">
                             <span class="info-label">客户：</span>
                             <span class="info-value" id="previewCustomer">-</span>
                         </div>
                         <div class="info-row">
                             <span class="info-label">客户电话：</span>
                             <span class="info-value" id="previewCustomerPhone">-</span>
                         </div>
                         <div class="info-row">
                             <span class="info-label">客户地址：</span>
                             <span class="info-value" id="previewCustomerAddress">-</span>
                         </div>
                         <div class="info-row">
                             <span class="info-label">操作人：</span>
                             <span class="info-value" id="previewOperator">-</span>
                         </div>
                     </div>
                 </div>
                 
                 <div class="preview-section">
                     <h4>商品明细</h4>
                     <div class="preview-table-container">
                         <table class="preview-table">
                             <thead>
                                 <tr>
                                     <th>商品名称</th>
                                     <th>规格</th>
                                     <th>数量（箱）</th>
                                     <th>数量（瓶）</th>
                                     <th>单价</th>
                                     <th>小计</th>
                                 </tr>
                             </thead>
                             <tbody id="previewOrderDetails">
                                 <!-- 商品明细将在这里显示 -->
                             </tbody>
                         </table>
                     </div>
                 </div>
                 
                 <div class="preview-section">
                     <h4>汇总信息</h4>
                     <div class="preview-summary">
                         <div class="summary-row">
                             <span class="summary-label">总金额：</span>
                             <span class="summary-value" id="previewTotalAmount">¥0.00</span>
                         </div>
                         <div class="summary-row">
                             <span class="summary-label">备注：</span>
                             <span class="summary-value" id="previewRemark">-</span>
                         </div>
                     </div>
                 </div>
             </div>
             <div class="form-actions" >
                 <button type="button" class="btn"  style="display: none" onclick="closeOrderPreviewModal()">返回编辑</button>
                 <button type="button" class="btn btn-primary" style="display: none"  onclick="confirmSaveOrder()">确认保存</button>
                 <button type="button" class="btn btn-secondary" onclick="closeOrderPreviewModal()">关闭预览</button>
             </div>
         </div>
     </div>
    
    <script src="https://unpkg.com/layui@2.8.18/dist/layui.js"></script>
    <script>
        let orders = [];
        let customers = [];
        let products = [];
        let currentPage = 1;
        let pageSize = 10;
        let currentOrderId = null;
        let orderDetails = [];
        // 页面加载完成后执行
        layui.use(['layer'], function(){
            var layer = layui.layer;
            loadOrders();
            loadOrderStats();
            loadCustomers();
            loadProducts();
        });
        
        // 加载订单统计数据
        function loadOrderStats() {
            fetch('/api/orders')
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        const allOrders = data.data;
                        document.getElementById('totalOrders').textContent = allOrders.length;
                        
                        const pending = allOrders.filter(o => o.status === 'PENDING').length;
                        const completed = allOrders.filter(o => o.status === 'COMPLETED').length;
                        const today = allOrders.filter(o => {
                            const orderDate = new Date(o.orderTime);
                            const today = new Date();
                            return orderDate.toDateString() === today.toDateString();
                        }).length;
                        
                        document.getElementById('pendingOrders').textContent = pending;
                        document.getElementById('completedOrders').textContent = completed;
                        document.getElementById('todayOrders').textContent = today;
                    }
                })
                .catch(error => console.error('加载订单统计失败:', error));
        }
        
        // 加载客户列表
        function loadCustomers() {
            fetch('/api/customers')
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        customers = data.data;
                        updateCustomerSelect();
                    }
                })
                .catch(error => console.error('加载客户列表失败:', error));
        }
        
        // 加载商品列表
        function loadProducts() {
            fetch('/api/products')
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        products = data.data;
                    }
                })
                .catch(error => console.error('加载商品列表失败:', error));
        }
        
        // 更新客户选择下拉框
        function updateCustomerSelect() {
            const customerSelect = document.getElementById('orderCustomer');
            
            // 移除之前的事件监听器（如果存在）
            const newCustomerSelect = customerSelect.cloneNode(true);
            customerSelect.parentNode.replaceChild(newCustomerSelect, customerSelect);
            
            newCustomerSelect.innerHTML = '<option value="">请选择客户</option>';
            customers.forEach(customer => {
                newCustomerSelect.innerHTML += `<option value="${customer.customerName}" data-phone="${customer.phone || ''}" data-address="${customer.address || ''}">${customer.customerName}</option>`;
            });
            
            // 添加客户选择事件监听器
            newCustomerSelect.addEventListener('change', function() {
                const selectedCustomerName = this.value;
                if (selectedCustomerName) {
                    const selectedOption = this.options[this.selectedIndex];
                    const customerPhone = selectedOption.getAttribute('data-phone');
                    const customerAddress = selectedOption.getAttribute('data-address');
                    
                    // 自动填充客户信息
                    document.getElementById('customerPhone').value = customerPhone || '';
                    document.getElementById('customerAddress').value = customerAddress || '';
                } else {
                    // 清空客户信息
                    document.getElementById('customerPhone').value = '';
                    document.getElementById('customerAddress').value = '';
                }
            });
        }
        
        // 加载订单列表
        function loadOrders() {
            const orderList = document.getElementById('orderList');
            orderList.innerHTML = '<div class="loading"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i><p>加载中...</p></div>';
            
            fetch('/api/orders/with-details')
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        orders = data.data;
                        renderOrderTable();
                    } else {
                        orderList.innerHTML = '<div class="no-data">加载失败: ' + data.message + '</div>';
                    }
                })
                .catch(error => {
                    console.error('加载订单列表失败:', error);
                    orderList.innerHTML = '<div class="no-data">加载失败，请检查网络连接</div>';
                });
        }
        
        // 渲染订单表格
        function renderOrderTable() {
            const orderList = document.getElementById('orderList');
            
            if (orders.length === 0) {
                orderList.innerHTML = '<div class="no-data">暂无订单数据</div>';
                return;
            }
            
            const startIndex = (currentPage - 1) * pageSize;
            const endIndex = startIndex + pageSize;
            const pageOrders = orders.slice(startIndex, endIndex);
            
            let tableHTML = `
                <table class="order-table">
                    <thead>
                        <tr>
                            <th>订单号</th>
                            <th>客户</th>
                            <th>客户电话</th>
                            <th>总金额</th>
                            <th>状态</th>
                            <th>操作人</th>
                            <th>订单时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
            `;
            
            pageOrders.forEach(order => {
                const statusClass = getStatusClass(order.status);
                const statusText = getStatusText(order.status);
                const orderTime = new Date(order.orderTime).toLocaleString('zh-CN');
                const totalAmount = order.totalAmount ? '¥' + order.totalAmount.toFixed(2) : '-';
                
                tableHTML += `
                    <tr>
                        <td>${order.orderNumber || '-'}</td>
                        <td>${order.customer || '-'}</td>
                        <td>${order.customerPhone || '-'}</td>
                        <td>${totalAmount}</td>
                        <td><span class="${statusClass}">${statusText}</span></td>
                        <td>${order.operator || '-'}</td>
                        <td>${orderTime}</td>
                        <td>
                            <div class="action-buttons">
                                <button class="btn btn-warning btn-sm" onclick="editOrder(${order.id})">
                                    <i class="layui-icon layui-icon-edit"></i>
                                </button>
                                <button class="btn btn-danger btn-sm" onclick="deleteOrder(${order.id})">
                                    <i class="layui-icon layui-icon-delete"></i>
                                </button>
                                ${order.status === 'PENDING' ? `
                                <button class="btn btn-success btn-sm" style="display: none" onclick="showStockOutModal(${order.id})">
                                    <i class="layui-icon layui-icon-release"></i> 出库
                                </button>
                                <button type="button" class="btn btn-info" onclick="showOrderPreview(${order.id})">
                                    <i class="layui-icon layui-icon-eye"></i> 预览
                                </button>` : ''}
                            </div>
                        </td>
                    </tr>
                `;
            });
            
            tableHTML += `
                    </tbody>
                </table>
            `;
            
            // 添加分页信息
            const totalPages = Math.ceil(orders.length / pageSize);
            const startRecord = startIndex + 1;
            const endRecord = Math.min(endIndex, orders.length);
            
            tableHTML += `
                <div style="margin-top: 20px; display: flex; justify-content: space-between; align-items: center; color: #666; font-size: 14px;">
                    <div>显示第 ${startRecord} - ${endRecord} 条，共 ${orders.length} 条记录</div>
                    <div>每页 ${pageSize} 条</div>
                </div>
            `;
            
            // 添加分页控件
            if (totalPages > 1) {
                tableHTML += '<div class="pagination">';
                
                if (currentPage > 1) {
                    tableHTML += `<button onclick="goToPage(${currentPage - 1})">上一页</button>`;
                }
                
                const startPage = Math.max(1, currentPage - 2);
                const endPage = Math.min(totalPages, currentPage + 2);
                
                for (let i = startPage; i <= endPage; i++) {
                    const activeClass = i === currentPage ? 'active' : '';
                    tableHTML += `<button class="${activeClass}" onclick="goToPage(${i})">${i}</button>`;
                }
                
                if (currentPage < totalPages) {
                    tableHTML += `<button onclick="goToPage(${currentPage + 1})">下一页</button>`;
                }
                
                tableHTML += '</div>';
            } else {
                tableHTML += '<div class="pagination">';
                tableHTML += '<button class="active" disabled>1</button>';
                tableHTML += '</div>';
            }
            
            orderList.innerHTML = tableHTML;
        }
        
        // 获取状态样式类
        function getStatusClass(status) {
            switch(status) {
                case 'PENDING': return 'status-pending';
                case 'PROCESSING': return 'status-processing';
                case 'COMPLETED': return 'status-completed';
                case 'CANCELLED': return 'status-cancelled';
                default: return '';
            }
        }
        
        // 获取状态文本
        function getStatusText(status) {
            switch(status) {
                case 'PENDING': return '待处理';
                case 'PROCESSING': return '处理中';
                case 'COMPLETED': return '已完成';
                case 'CANCELLED': return '已取消';
                default: return status || '-';
            }
        }
        
        // 搜索订单
        function searchOrders() {
            const orderNumber = document.getElementById('searchOrderNumber').value.trim();
            const customer = document.getElementById('searchCustomer').value.trim();
            
            if (!orderNumber && !customer) {
                loadOrders();
                return;
            }
            
            const orderList = document.getElementById('orderList');
            orderList.innerHTML = '<div class="loading"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i><p>搜索中...</p></div>';
            
            let searchUrl = '';
            if (orderNumber) {
                searchUrl = `/api/orders/number/${encodeURIComponent(orderNumber)}`;
            } else if (customer) {
                searchUrl = `/api/orders/customer?customer=${encodeURIComponent(customer)}`;
            }
            
            fetch(searchUrl)
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        orders = Array.isArray(data.data) ? data.data : [data.data];
                        currentPage = 1;
                        renderOrderTable();
                    } else {
                        orderList.innerHTML = '<div class="no-data">搜索失败: ' + data.message + '</div>';
                    }
                })
                .catch(error => {
                    console.error('搜索订单失败:', error);
                    orderList.innerHTML = '<div class="no-data">搜索失败，请检查网络连接</div>';
                });
        }
        
        // 按状态筛选
        function filterByStatus() {
            const status = document.getElementById('statusFilter').value;
            
            if (!status) {
                loadOrders();
                return;
            }
            
            const orderList = document.getElementById('orderList');
            orderList.innerHTML = '<div class="loading"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i><p>加载中...</p></div>';
            
            fetch(`/api/orders/status/${status}`)
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        orders = data.data;
                        currentPage = 1;
                        renderOrderTable();
                    } else {
                        orderList.innerHTML = '<div class="no-data">筛选失败: ' + data.message + '</div>';
                    }
                })
                .catch(error => {
                    console.error('按状态筛选失败:', error);
                    orderList.innerHTML = '<div class="no-data">筛选失败，请检查网络连接</div>';
                });
        }
        
        // 重置搜索
        function resetSearch() {
            document.getElementById('searchOrderNumber').value = '';
            document.getElementById('searchCustomer').value = '';
            document.getElementById('statusFilter').value = '';
            loadOrders();
        }
        
        // 显示新建订单模态框
        function showAddOrderModal() {
            document.getElementById('orderModalTitle').textContent = '新建订单';
            document.getElementById('orderForm').reset();
            document.getElementById('orderId').value = '';
            document.getElementById('orderNumber').value = '';
            // 设置默认操作人
            document.getElementById('operator').value = '浚县浚县胜宏食品';
            orderDetails = [];
            renderOrderDetails();
            updateTotalAmount();
            document.getElementById('orderModal').style.display = 'block';
        }
        
        // 编辑订单
        function editOrder(id) {
            const order = orders.find(o => o.id === id);
            if (!order) return;
            
            document.getElementById('orderModalTitle').textContent = '编辑订单';
            document.getElementById('orderId').value = order.id;
            document.getElementById('orderNumber').value = order.orderNumber || '';
            document.getElementById('orderCustomer').value = order.customer || '';
            document.getElementById('customerPhone').value = order.customerPhone || '';
            document.getElementById('customerAddress').value = order.customerAddress || '';
            document.getElementById('operator').value = order.operator || '浚县浚县胜宏食品';
            document.getElementById('remark').value = order.remark || '';
            
            // 加载订单明细
            orderDetails = order.orderDetails || [];
            
            // 确保每个明细的小计都正确计算
            orderDetails.forEach((detail, index) => {
                updateDetailTotalPrice(index);
            });
            
            renderOrderDetails();
            updateTotalAmount();
            
            document.getElementById('orderModal').style.display = 'block';
        }
        
        // 添加订单明细行
        function addOrderDetail() {
            const detail = {
                id: Date.now(), // 临时ID
                productId: '',
                productName: '',
                specification: '',
                quantity: 1,
                unitPrice: 0,
                totalPrice: 0,
                unit: '',
                boxUnit: ''
            };
            orderDetails.push(detail);
            renderOrderDetails();
        }
        
        // 移除订单明细行
        function removeOrderDetail(index) {
            orderDetails.splice(index, 1);
            renderOrderDetails();
            updateTotalAmount();
        }
        
                 // 渲染订单明细表格
         function renderOrderDetails() {
             const tbody = document.getElementById('orderDetailsBody');
             tbody.innerHTML = '';
             
             orderDetails.forEach((detail, index) => {
                 const row = document.createElement('tr');
                 row.innerHTML = `
                     <td>
                         <select class="product-select" onchange="updateProductInfo(${index}, this.value)">
                             <option value="">请选择商品</option>
                             ${products.map(p => `<option value="${p.id}" ${detail.productId == p.id ? 'selected' : ''}>${p.productName}</option>`).join('')}
                         </select>
                     </td>
                     <td>
                         <input type="number" value="${detail.quantity}" min="1" style="width: 60px; padding: 4px;" onchange="updateQuantity(${index}, this.value)">
                     </td>
                     <td>
                         <select style="width: 80px; padding: 4px; font-size: 12px;" onchange="updateUnit(${index}, this.value)">
                             ${getUnitOptions(detail)}
                         </select>
                     </td>
                     <td>
                         <input type="number" value="${detail.unitPrice}" step="0.01" min="0" style="width: 80px; padding: 4px;" onchange="updateUnitPrice(${index}, this.value)">
                     </td>
                     <td>¥${(parseFloat(detail.totalPrice) || 0).toFixed(2)}</td>
                     <td>
                         <button type="button" class="remove-detail-btn" onclick="removeOrderDetail(${index})">删除</button>
                     </td>
                 `;
                 tbody.appendChild(row);
             });
         }
        
        // 获取商品单位选项
        function getUnitOptions(detail) {
            const product = products.find(p => p.id == detail.productId);
            if (!product) {
                return '<option value="">请先选择商品</option>';
            }
            
            console.log('Product for unit options:', product); // 调试日志
            console.log('Detail unit:', detail.unit); // 调试日志
            
            let options = '';
            
            // 添加商品的单位选项
            if (product.unit) {
                options += `<option value="${product.unit}" ${detail.unit === product.unit ? 'selected' : ''}>${product.unit}</option>`;
            }
            
            // 添加商品的箱单位选项
            if (product.boxUnit && product.boxUnit !== product.unit) {
                options += `<option value="${product.boxUnit}" ${detail.unit === product.boxUnit ? 'selected' : ''}>${product.boxUnit}</option>`;
            }
            
            // 如果没有单位信息，提供默认选项
            if (!product.unit && !product.boxUnit) {
                options += '<option value="个" ${detail.unit === "个" ? "selected" : ""}>个</option>';
            }
            
            console.log('Generated options:', options); // 调试日志
            return options;
        }
        
        // 更新商品信息
        function updateProductInfo(index, productId) {
            const product = products.find(p => p.id == productId);
            if (product) {
                console.log('Selected product:', product); // 调试日志
                orderDetails[index].productId = product.id;
                orderDetails[index].productName = product.productName;
                orderDetails[index].specification = product.specification || '';
                orderDetails[index].unitPrice = product.price || 0;
                // 设置商品的单位和箱单位
                orderDetails[index].boxUnit = product.boxUnit || '';
                // 默认选择商品的单位
                orderDetails[index].unit = product.unit || (product.boxUnit || '个');
                console.log('Updated order detail:', orderDetails[index]); // 调试日志
                
                // 更新价格计算
                updateDetailTotalPrice(index);
                updateTotalAmount();
                
                // 重新渲染表格以显示更新后的数据
                renderOrderDetails();
            }
        }
        
        // 更新数量
        function updateQuantity(index, quantity) {
            const newQuantity = parseInt(quantity) || 1;
            orderDetails[index].quantity = newQuantity;
            console.log(`更新数量 [${index}]: ${newQuantity}`);
            updateDetailTotalPrice(index);
            updateTotalAmount();
            // 重新渲染表格以显示更新后的小计金额
            renderOrderDetails();
        }
        
                 // 更新单价
         function updateUnitPrice(index, unitPrice) {
             const newUnitPrice = parseFloat(unitPrice) || 0;
             orderDetails[index].unitPrice = newUnitPrice;
             console.log(`更新单价 [${index}]: ${newUnitPrice}`);
             updateDetailTotalPrice(index);
             updateTotalAmount();
             // 重新渲染表格以显示更新后的小计金额
             renderOrderDetails();
         }
         
         // 更新单位
         function updateUnit(index, unit) {
             orderDetails[index].unit = unit;
             // 单位变更不影响价格计算，只需要重新渲染显示
             renderOrderDetails();
         }
        
        // 更新明细小计
        function updateDetailTotalPrice(index) {
            const detail = orderDetails[index];
            const quantity = parseInt(detail.quantity) || 0;
            const unitPrice = parseFloat(detail.unitPrice) || 0;
            detail.totalPrice = quantity * unitPrice;
            
            console.log(`更新明细小计 [${index}]: 数量=${quantity}, 单价=${unitPrice}, 小计=${detail.totalPrice}`);
        }
        
        // 更新总金额
        function updateTotalAmount() {
            const total = orderDetails.reduce((sum, detail) => sum + (parseFloat(detail.totalPrice) || 0), 0);
            const totalElement = document.getElementById('totalAmount');
            if (totalElement) {
                totalElement.value = total.toFixed(2);
                console.log(`更新总金额: ${total.toFixed(2)}`);
            } else {
                console.error('找不到总金额输入框元素');
            }
        }
        
        // 关闭订单模态框
        function closeOrderModal() {
            document.getElementById('orderModal').style.display = 'none';
        }
        
        // 删除订单
        function deleteOrder(id) {
            layui.use(['layer'], function(){
                var layer = layui.layer;
                layer.confirm('确定要删除这个订单吗？', {
                    title: '确认删除',
                    btn: ['确定', '取消']
                }, function(index) {
                    fetch(`/api/orders/${id}`, {
                        method: 'DELETE'
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.code === 200) {
                            layer.msg('删除成功', {icon: 1});
                            loadOrders();
                            loadOrderStats();
                        } else {
                            layer.msg('删除失败: ' + data.message, {icon: 2});
                        }
                    })
                    .catch(error => {
                        console.error('删除订单失败:', error);
                        layer.msg('删除失败，请检查网络连接', {icon: 2});
                    });
                    layer.close(index);
                });
            });
        }
        
        // 显示出库模态框
        function showStockOutModal(orderId) {
            const order = orders.find(o => o.id === orderId);
            if (!order) return;
            
            currentOrderId = orderId;
            document.getElementById('stockOutOrderInfo').innerHTML = `
                <p><strong>订单号：</strong>${order.orderNumber}</p>
                <p><strong>客户：</strong>${order.customer}</p>
                <p><strong>总金额：</strong>¥${order.totalAmount ? order.totalAmount.toFixed(2) : '0.00'}</p>
                <p><strong>状态：</strong>${getStatusText(order.status)}</p>
            `;
            document.getElementById('stockOutOperator').value = '';
            document.getElementById('stockOutModal').style.display = 'block';
        }
        
        // 关闭出库模态框
        function closeStockOutModal() {
            document.getElementById('stockOutModal').style.display = 'none';
            currentOrderId = null;
        }
        
        // 确认出库
        function confirmStockOut() {
            const operator = document.getElementById('stockOutOperator').value.trim();
            if (!operator) {
                layui.use(['layer'], function(){
                    layui.layer.msg('请输入操作人', {icon: 2});
                });
                return;
            }
            
            fetch(`/api/stock-out/from-order?orderId=${currentOrderId}&operator=${encodeURIComponent(operator)}`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    layui.use(['layer'], function(){
                        layui.layer.msg('出库成功', {icon: 1});
                    });
                    closeStockOutModal();
                    loadOrders();
                    loadOrderStats();
                } else {
                    layui.use(['layer'], function(){
                        layui.layer.msg('出库失败: ' + data.message, {icon: 2});
                    });
                }
            })
            .catch(error => {
                console.error('出库失败:', error);
                layui.use(['layer'], function(){
                    layui.layer.msg('出库失败，请检查网络连接', {icon: 2});
                });
            });
        }
        
        // 分页
        function goToPage(page) {
            currentPage = page;
            renderOrderTable();
        }
        
        // 改变每页显示条数
        function changePageSize() {
            const newPageSize = parseInt(document.getElementById('pageSizeSelect').value);
            pageSize = newPageSize;
            currentPage = 1;
            renderOrderTable();
        }
        
                 // 表单提交
         document.getElementById('orderForm').addEventListener('submit', function(e) {
             e.preventDefault();
             
             // 验证必填字段
             const customer = document.getElementById('orderCustomer').value;
             if (!customer) {
                 layui.use(['layer'], function(){
                     layui.layer.msg('请选择客户', {icon: 2});
                 });
                 return;
             }
             
             if (orderDetails.length === 0) {
                 layui.use(['layer'], function(){
                     layui.layer.msg('请至少添加一个商品', {icon: 2});
                 });
                 return;
             }

             // 直接保存订单，不进行预览
             confirmSaveOrder();
         });
        
        // 导航函数
        function goToHome() {
            window.location.href = 'index.html';
        }
        
        function goToCustomers() {
            window.location.href = 'customers.html';
        }
        
        function goToProducts() {
            window.location.href = 'products.html';
        }
        
        function goToCategories() {
            window.location.href = 'categories.html';
        }
        
        function showOrders() {
            // 当前页面，无需跳转
        }
        
        function goToStockIn() {
            alert('入库管理功能开发中...');
        }
        
        function goToStockOut() {
            alert('出库管理功能开发中...');
        }
        
        function goToReports() {
            alert('统计报表功能开发中...');
        }
        
        function goToSettings() {
            alert('系统设置功能开发中...');
        }
        
                 // 显示订单预览
         function showOrderPreview(orderId) {
             // 验证订单ID
             if (!orderId) {
                 alert('订单ID不能为空');
                 return;
             }
             
             // 显示加载状态
             document.getElementById('orderPreviewModal').style.display = 'block';
             document.getElementById('previewOrderNumber').textContent = '加载中...';
             document.getElementById('previewCustomer').textContent = '加载中...';
             document.getElementById('previewCustomerPhone').textContent = '加载中...';
             document.getElementById('previewCustomerAddress').textContent = '加载中...';
             document.getElementById('previewOperator').textContent = '加载中...';
             document.getElementById('previewTotalAmount').textContent = '加载中...';
             document.getElementById('previewRemark').textContent = '加载中...';
             
             // 从后端获取订单详情
             fetch(`/api/orders/${orderId}/with-details`)
                 .then(response => response.json())
                 .then(data => {
                     console.log('API Response:', data); // 调试日志
                     try {
                         if (data.code === 200) {
                             const order = data.data;
                             console.log('Order data:', order); // 调试日志
                             
                             // 填充预览信息
                             document.getElementById('previewOrderNumber').textContent = order.orderNumber || '-';
                             document.getElementById('previewCustomer').textContent = order.customer || '-';
                             document.getElementById('previewCustomerPhone').textContent = order.customerPhone || '-';
                             document.getElementById('previewCustomerAddress').textContent = order.customerAddress || '-';
                             document.getElementById('previewOperator').textContent = order.operator || '-';
                             document.getElementById('previewTotalAmount').textContent = '¥' + (order.totalAmount ? parseFloat(order.totalAmount).toFixed(2) : '0.00');
                             document.getElementById('previewRemark').textContent = order.remark || '-';
                             
                             // 渲染商品明细
                             renderPreviewOrderDetailsFromData(order.orderDetails || []);
                         } else {
                             alert('获取订单信息失败：' + data.message);
                             document.getElementById('orderPreviewModal').style.display = 'none';
                         }
                     } catch (error) {
                         console.error('处理订单数据时出错:', error);
                         alert('处理订单数据时出错，请稍后重试');
                         document.getElementById('orderPreviewModal').style.display = 'none';
                     }
                 })
                 .catch(error => {
                     console.error('获取订单信息失败:', error);
                     alert('获取订单信息失败，请稍后重试');
                     document.getElementById('orderPreviewModal').style.display = 'none';
                 });
         }
         
         // 渲染预览商品明细（从表单数据）
         function renderPreviewOrderDetails() {
             const tbody = document.getElementById('previewOrderDetails');
             tbody.innerHTML = '';
             
             orderDetails.forEach(detail => {
                 if (detail.productName) {
                     const row = document.createElement('tr');
                     
                     // 根据单位计算箱数和瓶数
                     let boxes = 0;
                     let bottles = 0;
                     const totalQuantity = detail.quantity || 0;
                     
                     if (detail.unit === '箱') {
                         boxes = totalQuantity;
                         bottles = 0;
                     } else if (detail.unit === '瓶') {
                         const bottlesPerBox = 24; // 假设每箱24瓶，可根据实际情况调整
                         boxes = Math.floor(totalQuantity / bottlesPerBox);
                         bottles = totalQuantity % bottlesPerBox;
                     } else {
                         // 其他单位（个、件等）按瓶计算
                         bottles = totalQuantity;
                         boxes = 0;
                     }
                     
                     row.innerHTML = `
                         <td>${detail.productName}</td>
                         <td>${detail.specification || '-'}</td>
                         <td>${boxes}</td>
                         <td>${bottles}</td>
                         <td>¥${detail.unitPrice ? detail.unitPrice.toFixed(2) : '0.00'}</td>
                         <td>¥${detail.totalPrice ? detail.totalPrice.toFixed(2) : '0.00'}</td>
                     `;
                     tbody.appendChild(row);
                 }
             });
             
             // 如果没有商品明细，显示提示
             if (orderDetails.length === 0 || !orderDetails.some(d => d.productName)) {
                 tbody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #999;">暂无商品明细</td></tr>';
             }
         }
         
         // 渲染预览商品明细（从后端数据）
         function renderPreviewOrderDetailsFromData(orderDetailsData) {
             console.log('Rendering order details:', orderDetailsData); // 调试日志
             try {
                 const tbody = document.getElementById('previewOrderDetails');
                 if (!tbody) {
                     console.error('找不到预览商品明细表格元素');
                     return;
                 }
                 tbody.innerHTML = '';
                 
                 if (!Array.isArray(orderDetailsData)) {
                     console.error('订单明细数据不是数组:', orderDetailsData);
                     tbody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #999;">数据格式错误</td></tr>';
                     return;
                 }
                 
                 orderDetailsData.forEach(detail => {
                 if (detail.productName) {
                     const row = document.createElement('tr');
                     
                     // 根据单位计算箱数和瓶数
                     let boxes = 0;
                     let bottles = 0;
                     const totalQuantity = detail.quantity || 0;
                     
                     if (detail.unit === '箱') {
                         boxes = totalQuantity;
                         bottles = 0;
                     } else if (detail.unit === '瓶') {
                         const bottlesPerBox = 24; // 假设每箱24瓶，可根据实际情况调整
                         boxes = Math.floor(totalQuantity / bottlesPerBox);
                         bottles = totalQuantity % bottlesPerBox;
                     } else {
                         // 其他单位（个、件等）按瓶计算
                         bottles = totalQuantity;
                         boxes = 0;
                     }
                     
                     row.innerHTML = `
                         <td>${detail.productName}</td>
                         <td>${detail.specification || '-'}</td>
                         <td>${boxes}</td>
                         <td>${bottles}</td>
                         <td>¥${detail.unitPrice ? parseFloat(detail.unitPrice).toFixed(2) : '0.00'}</td>
                         <td>¥${detail.totalPrice ? parseFloat(detail.totalPrice).toFixed(2) : '0.00'}</td>
                     `;
                     tbody.appendChild(row);
                 }
             });
             
             // 如果没有商品明细，显示提示
             if (orderDetailsData.length === 0 || !orderDetailsData.some(d => d.productName)) {
                 tbody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #999;">暂无商品明细</td></tr>';
             }
             } catch (error) {
                 console.error('渲染订单明细时出错:', error);
                 const tbody = document.getElementById('previewOrderDetails');
                 if (tbody) {
                     tbody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #999;">渲染出错</td></tr>';
                 }
             }
         }
         
         // 关闭订单预览模态框
         function closeOrderPreviewModal() {
             document.getElementById('orderPreviewModal').style.display = 'none';
         }
         
         // 确认保存订单
         function confirmSaveOrder() {
             const orderId = document.getElementById('orderId').value;
             const orderData = {
                 orderNumber: document.getElementById('orderNumber').value,
                 customer: document.getElementById('orderCustomer').value,
                 customerPhone: document.getElementById('customerPhone').value,
                 customerAddress: document.getElementById('customerAddress').value,
                 totalAmount: parseFloat(document.getElementById('totalAmount').value) || 0,
                 operator: document.getElementById('operator').value,
                 remark: document.getElementById('remark').value,
                 orderDetails: orderDetails
             };
             
             const url = orderId ? `/api/orders/${orderId}` : '/api/orders';
             const method = orderId ? 'PUT' : 'POST';
             
             fetch(url, {
                 method: method,
                 headers: {
                     'Content-Type': 'application/json'
                 },
                 body: JSON.stringify(orderData)
             })
             .then(response => response.json())
             .then(data => {
                 if (data.code === 200) {
                     layui.use(['layer'], function(){
                         var layer = layui.layer;
                         layer.msg(orderId ? '更新成功' : '创建成功', {icon: 1});
                     });
                     closeOrderPreviewModal();
                     closeOrderModal();
                     loadOrders();
                     loadOrderStats();
                 } else {
                     layui.use(['layer'], function(){
                         var layer = layui.layer;
                         layer.msg('操作失败: ' + data.message, {icon: 2});
                     });
                 }
             })
             .catch(error => {
                 console.error('保存订单失败:', error);
                 layui.use(['layer'], function(){
                     var layer = layui.layer;
                     layer.msg('保存失败，请检查网络连接', {icon: 2});
                 });
             });
         }
         
         // 点击模态框外部关闭
         window.onclick = function(event) {
             const orderModal = document.getElementById('orderModal');
             const stockOutModal = document.getElementById('stockOutModal');
             const orderPreviewModal = document.getElementById('orderPreviewModal');
             if (event.target === orderModal) {
                 closeOrderModal();
             }
             if (event.target === stockOutModal) {
                 closeStockOutModal();
             }
             if (event.target === orderPreviewModal) {
                 closeOrderPreviewModal();
             }
         }
    </script>
</body>
</html> 